﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Security;
using Popw.LiveBlog.Services;

namespace Popw.LiveBlog.Controllers
{
	public class HomeController : Controller
	{
		private readonly IContentService _contentService;
		private readonly ITimeFormattingService _timeFormattingService;

		public HomeController(IContentService contentService, ITimeFormattingService timeFormattingService)
		{
			_contentService = contentService;
			_timeFormattingService = timeFormattingService;
		}

		public ViewResult Index()
		{
			var allItems = _contentService.GetTop();
			ViewBag.OldestID = _contentService.GetOldestID();
			return View(allItems);
		}

		[HttpPost]
		public JsonResult GetMore(string lastTime)
		{
			var parsedTime = DateTime.Parse(lastTime);
			var moreItems = _contentService.GetGetTopContentItemsAfterTimeTop(parsedTime);
			return Json(moreItems);
		}

		public JsonResult GetTimes(string[] times)
		{
			var list = new List<TimePairs>();
			if (times == null || times.Length == 0)
				return Json(list);
			foreach (var item in times)
			{
				var time = DateTime.Parse(item);
				list.Add(new TimePairs { Key = item, Value = _timeFormattingService.GetFormattedTime(time) });
			}
			return Json(list);
		}

		private class TimePairs
		{
			public string Key { get; set; }
			public string Value { get; set; }
		}

		public ViewResult Login()
		{
			return View();
		}

		[HttpPost]
		public ActionResult Login(string name, string password)
		{
			if (FormsAuthentication.Authenticate(name, password))
			{
				FormsAuthentication.SetAuthCookie(name, true);
				return RedirectToAction("Index", "Admin");
			}
			ModelState.AddModelError("name", "Bad login!");
			return View();
		}

		public RedirectToRouteResult Logout()
		{
			FormsAuthentication.SignOut();
			return RedirectToAction("Index");
		}

		public ActionResult Item(int id)
		{
			var item = _contentService.Item(id);
			if (item == null)
				return HttpNotFound("Not found");
			return View(item);
		}
	}
}